package com.itheima.common.llm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "llm")
public class GreenContentScan {

    private String apiKey;
    private String apiUrl;

    /**
     * 内容审核方法（与GreenTextScan返回格式对齐）
     * @param content 待审核的文本内容
     * @return 审核结果Map，包含suggestion和label；异常时返回null
     */
    public Map<String, String> textScan(String content) {
        // 创建Apache HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 构建POST请求
            HttpPost httpPost = new HttpPost(apiUrl);

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "Bearer " + apiKey);

            // 构建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("model", "moderation");
            requestBody.put("input", content);

            // 设置请求体内容
            httpPost.setEntity(new StringEntity(
                    requestBody.toString(),
                    StandardCharsets.UTF_8.name()
            ));

            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

                    // 处理响应结果（假设API返回格式包含results数组，内部有suggestion和label字段）
                    if (response.getStatusLine().getStatusCode() == 200) {
                        JSONObject result = JSON.parseObject(responseBody);
                        Map<String, String> resultMap = new HashMap<>();

                        // 解析审核结果（根据实际API响应结构调整）
                        JSONArray results = result.getJSONArray("result_list");
                        if (results != null && !results.isEmpty()) {
                            JSONObject firstResult = results.getJSONObject(0);
                            String suggestion = firstResult.getString("risk_level");
                            String label = firstResult.getString("risk_type");

                            // 若不通过，返回建议和标签
                            if (!"PASS".equals(suggestion)) {
                                resultMap.put("suggestion", suggestion);
                                resultMap.put("label", label);
                                return resultMap;
                            }
                        }

                        // 所有检测通过
                        resultMap.put("suggestion", "PASS");
                        return resultMap;
                    } else {

                        // HTTP状态非200时返回null（与原逻辑一致）
                        return null;
                    }
                }
            }
        } catch (IOException e) {

            e.printStackTrace();
            // 异常时返回null（与原逻辑一致）
            return null;
        }
        return null;
    }

    /**
     * 图片审核方法（与文本审核格式对齐）
     * @param imageList 待审核的图片字节列表
     * @return 审核结果Map，包含suggestion和label；异常时返回null
     */
    public Map<String, String> imageScan(List<byte[]> imageList) {
        // 构建图片对象数组（type+image_url结构，url存储Base64）
        JSONArray imagesArray = new JSONArray();
        for (byte[] imageBytes : imageList) {
            // 将图片字节转为Base64编码
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);

            // 构建image_url对象（url字段存储Base64）
            JSONObject imageUrlObj = new JSONObject();
            imageUrlObj.put("url", base64Image);

            // 构建单个图片对象（包含type和image_url）
            JSONObject imageObj = new JSONObject();
            imageObj.put("type", "image_url");
            imageObj.put("image_url", imageUrlObj);

            imagesArray.add(imageObj);
        }

        // 创建Apache HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 构建POST请求
            HttpPost httpPost = new HttpPost(apiUrl);

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "Bearer " + apiKey);

            // 构建请求体（input为图片对象数组）
            JSONObject requestBody = new JSONObject();
            requestBody.put("model", "moderation");
            requestBody.put("input", imagesArray);

            // 设置请求体内容
            httpPost.setEntity(new StringEntity(
                    requestBody.toString(),
                    StandardCharsets.UTF_8.name()
            ));

            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

                    // 处理响应结果（假设API返回格式与文本审核类似）
                    if (response.getStatusLine().getStatusCode() == 200) {
                        JSONObject result = JSON.parseObject(responseBody);
                        Map<String, String> resultMap = new HashMap<>();

                        JSONArray results = result.getJSONArray("result_list");
                        if (results != null && !results.isEmpty()) {
                            JSONObject firstResult = results.getJSONObject(0);
                            String suggestion = firstResult.getString("risk_level");
                            String label = firstResult.getString("risk_type");

                            if (!"PASS".equals(suggestion)) {
                                resultMap.put("suggestion", suggestion);
                                resultMap.put("label", label);
                                return resultMap;
                            }
                        }

                        resultMap.put("suggestion", "PASS");
                        return resultMap;
                    } else {
                        return null;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }
}